<?php
/**
 * @Author:      famous
 * @DateTime:    2017-05-12 11:12:22
 * @Description: 用于 scs 企业用户管理
 */
class ScsCompanyController extends BaseController {


    /**
     * @Author:      lyt
     * @DateTime:  2017-05-27 15:59:44
     * @Description: 用户的账期信息
     */
    public function accountDayStatus(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'user_id' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("scs_error.login_token_error_21005");
                break;
            }

            //传入参数
            $token = Input::get('token');
            $user_id = Input::get("user_id");

            //传入参数
            $response = array('code' => 0, 'msg' => 'ok');
            $sc_user=$this->verificationSCSUserToken($token,$response);
            if(is_null($sc_user)){
                break;
            }

            $c=Companys::find($user_id);
            if($c){
                $check=Companys::accountDayStatus($c);
            }           
            
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array(
                "accounting_cycle"=>isset($c)?$c->accounting_cycle:"",
                "collection_cycle"=>isset($c)?$c->collection_cycle:"",
                "start_month"=>isset($c)?$c->start_year.'年'.$c->start_month."月":"",
                "accountstatus"=>isset($check)&&$check["day_status"]=='逾期（禁止挂帐）'?1:0,
            ));
        } while (false);
        Log::info("info", array("system" => "scs" ,"model" => "company", "event" => "detail", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    /*
     * 企业详细信息
     * http://api.anhui.com/v1/scs/company/detail?token=b5ce501fdbf0ad0436a89ac8cbaef1f6&user_id=1000010444
     * */
    public function detail(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'user_id' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("scs_error.login_token_error_21005");
                break;
            }

            //传入参数
            $token = Input::get('token');
            $user_id = Input::get("user_id");

            //传入参数
            $response = array('code' => 0, 'msg' => 'ok');
            $sc_user=$this->verificationSCSUserToken($token,$response);
            if(is_null($sc_user)){
                break;
            }

            $companys = Users::orderby("users.created_at","desc")
                ->leftJoIn("user_account","users.id","=","user_account.user_id")
                ->leftJoIn("companys","companys.id","=","users.id")
                ->leftJoIn("user_label_activity","user_label_activity.user_id","=","users.id")
                ->leftJoIn("user_label_activity_type","user_label_activity_type.id","=","user_label_activity.lable_id")
                ->select("users.id",'users.real_name','users.status','users.phone','users.is_prior',"user_account.balance as balance","user_account.credit as credit","companys.*","user_label_activity_type.name as user_label_activity")
                ->where('users.type',2)
                ->where('users.id',$user_id)
                ->get()
                ->toArray();
            $ccount=UserCarInfo::where("user_id",$user_id)->where("status",1)->count();
            $count = count($companys);
            $result = array(
                'count' => $count,
                "car_count"=>$ccount,
                'companys' => $companys
            );
            $response = array('code' => 0, 'msg' => 'ok', 'result' => $result);
        } while (false);
        Log::info("info", array("system" => "scs" ,"model" => "company", "event" => "detail", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }


    /**
     * @Author:      famous
     * @DateTime:    2017-05-12 11:12:22
     * @Description: 企业用户列表
     * http://api.anhui.com/v1/scs/company/lists?token=b5ce501fdbf0ad0436a89ac8cbaef1f6
     */
    public function lists()
    {
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required'
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("scs_error.login_token_error_21005");
                break;
            }

            //传入参数
            $token = Input::get('token');
            $name = Input::get('name');
            $page_size = Input::get("page_size", 10);
            $page = Input::get("page", 0);

            //传入参数
            $response = array('code' => 0, 'msg' => 'ok');
            $sc_user=$this->verificationSCSUserToken($token,$response);
            if(is_null($sc_user)){                
                break;
            }

            $companys = Users::orderby("users.created_at","desc")
                ->leftJoIn("user_account","users.id","=","user_account.user_id")
                ->select("users.id",'users.real_name','users.status',"user_account.balance as balance","user_account.credit as credit")
                ->where('users.type',2)
                ->where('users.id','!=','1000000000')
                ->skip($page_size*($page-1))
                ->take($page_size);

            $count = Users::orderby("users.created_at","desc")
                ->leftJoIn("user_account","users.id","=","user_account.user_id")
                ->select("users.id",'users.real_name','users.status',"user_account.balance as balance","user_account.credit as credit")
                ->where('users.type',2)
                ->where('users.id','!=','1000000000');

            if(!is_null($name)){
                $companys->where('users.real_name','like','%'.$name.'%');
                $count->where('users.real_name','like','%'.$name.'%');
            }
            $companys = $companys->get()->toArray();
            $count = $count->count();

            foreach ($companys as &$_company){
                $_company['balance'] = $_company['balance']/100;
                $_company['credit'] = $_company['credit']/100;
                $company = Companys::find($_company['id']);
                $accountDayStatus = Companys::accountDayStatus($company);
                $_company['credit_status'] = $accountDayStatus['day_status'];
            }

            $result = array(
                'count' => $count,
                'companys' => $companys
            );
            $response = array('code' => 0, 'msg' => 'ok', 'result' => $result);
        } while (false);
        Log::info("info", array("system" => "scs" ,"model" => "company", "event" => "lists", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    //添加车辆用的城市列表
    public function getCommonCities(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required'
            )
        );
        do {
            if ($validator->fails()) {
                $response = Lang::get("scs_error.login_token_error_21005");
                break;
            }

            //传入参数
            $token = Input::get('token');

            //传入参数
            $response = array('code' => 0, 'msg' => 'ok');
            $sc_user = $this->verificationSCSUserToken($token, $response);
            if (is_null($sc_user)) {
                break;
            }
            $citys = CommonCity::all();
            if($citys) {
                $response = array('code' => 0, 'msg' => 'ok', 'result' => $citys);
            }else{
                $response = array('code' => -1, 'msg' => 'fail', 'result' => array());
            }
        } while (false);
        Log::info("info", array("system" => "scs" ,"model" => "company", "event" => "getCommonCities", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     * @Author:      zy
     * @DateTime:  2017-08-16
     * @Description: 企业逾期订单
     */
    public function overdueOrders(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'user_id'=> 'required'
            )
        );
        do {
            if ($validator->fails()) {
                $response = Lang::get("scs_error.login_token_error_21005");
                break;
            }

            //传入参数
            $res = [];
            $token = Input::get('token');
            $response = array('code' => 0, 'msg' => 'ok');
            $sc_user = $this->verificationSCSUserToken($token, $response);
            if (is_null($sc_user)) {
                break;
            }
            $user_id = Input::get('user_id');  //用户id
            $list = Orders::leftJoin('maintenance_shops','orders.shop_id','=','maintenance_shops.id')->leftJoin('order_pay_record','orders.order_id','=','order_pay_record.order_id')
                ->where('orders.pay_user_id',$user_id)->whereIn('orders.pay_type',[6,9])->where('order_pay_record.pay_type',6)->where('order_pay_record.status',1)
                ->whereIn('orders.status',array(1018,1017,1217,1317,1417))->where('orders.verify_status','0')->groupBy('orders.order_id')->orderBy('orders.pay_time','asc')
                ->select(DB::raw('orders.order_id,orders.pay_time,orders.order_type,sum(order_pay_record.amount) as amount,maintenance_shops.name'))->get()->toArray();
            $list1 = CarWashOrder::leftJoin('maintenance_shops','car_wash_order.shop_id','=','maintenance_shops.id')->leftJoin('car_wash_order_pay_record','car_wash_order.order_id','=','car_wash_order_pay_record.order_id')
                ->where('car_wash_order.user_id',$user_id)->whereIn('car_wash_order.pay_type',[6,9])->where('car_wash_order_pay_record.pay_type',6)->where('car_wash_order_pay_record.status',1)
                ->whereIn('car_wash_order.status',array(1018,1017,1217,1317,1417))->where('car_wash_order.verify_status','0')->groupBy('car_wash_order.order_id')->orderBy('car_wash_order.pay_time','asc')
                ->select(DB::raw('car_wash_order.order_id,car_wash_order.pay_time,3 as order_type,sum(car_wash_order_pay_record.amount) as amount,maintenance_shops.name'))->get()->toArray();
            $list2 = ServiceCardOrder::leftJoin('maintenance_shops','service_card_order.shop_id','=','maintenance_shops.id')->leftJoin('service_card_order_pay_record','service_card_order.order_id','=','service_card_order_pay_record.order_id')
                ->where('service_card_order.user_id',$user_id)->whereIn('service_card_order.pay_type',[6,9])->where('service_card_order_pay_record.pay_type',6)->where('service_card_order_pay_record.status',1)
                ->whereIn('service_card_order.status',array(1018,1017,1217,1317,1417))->where('service_card_order.verify_status','0')->groupBy('service_card_order.order_id')->orderBy('service_card_order.pay_time','asc')
                ->select(DB::raw('service_card_order.order_id,service_card_order.pay_time,4 as order_type,sum(service_card_order_pay_record.amount) as amount,maintenance_shops.name'))->get()->toArray();
            $list = array_merge($list , $list1 , $list2);
            $sort = array(
                'direction' => 'SORT_ASC', //排序顺序标志 SORT_DESC 降序；SORT_ASC 升序
                'field'     => 'pay_time',       //排序字段
            );
            $list = $this->resortArrayASC($sort,$list);
            $company = Companys::find($user_id);
            $now_time = strtotime(date('Y-m',time()));
            $y_m_time = strtotime($company->start_year . '-' . $company->start_month);
            $ele = (is_null($company->start_year) || is_null($company->start_month) || is_null($company->accounting_cycle) || is_null($company->collection_cycle)|| $company->accounting_cycle == 0) ? 1 : 0;
            foreach($list as $li){
                $begin_time = $li['pay_time'];
                $begin_time = strtotime($begin_time);
                $be_time = strtotime(date('Y-m',$begin_time));
                $end_time = Companys::getEndTime($begin_time,$y_m_time,$company->accounting_cycle,$company->collection_cycle);
//                $yuqi_time = strtotime(date('Y-m',$be_time) . ' +' . ($company->accounting_cycle + $company->collection_cycle) .' month' );
                if ($li['amount'] != 0 &&($ele == 1 || !($y_m_time <= $be_time && $now_time < $end_time))) {
                    $res[] = $li;
                }
            }
            foreach ($res as &$re){
                if($re['order_type'] == 1){
                    $re['order_type'] = '服务单';
                }elseif($re['order_type'] == 2){
                    $re['order_type'] = '零售单';
                }elseif($re['order_type'] == 3){
                    $re['order_type'] = '洗车单';
                }elseif($re['order_type'] == 4){
                    $re['order_type'] = '套餐卡单';
                }
                $re['amount'] = $re['amount'] / 100;
            }
            
        } while (false);
        $response = array('code' => 0, 'msg' => 'ok', 'result' => $res);
        Log::info("info", array("system" => "scs" ,"model" => "company", "event" => "overdueOrders", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     * @author zh
     * @datetime 20170705
     * @Description  二维数组排序
     */
    function resortArrayASC($sort,$arr){
        foreach ($arr as $key => $row) {
            $volume[$key]  = $row[$sort['field']];
        }
        array_multisort($volume, SORT_ASC, $arr);
        return $arr;
    }
}